package com.shadow.cloud.security.utils.ant;

import com.shadow.cloud.security.entity.OrgEntity;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public final class AntUtils {

    private AntUtils() {
    }

    public static List<AntTreeNode> convertToTree(List<OrgEntity> list) {
        // 1. 转换 A -> DTO
        List<AntTreeNode> dtoList = list.stream()
                .map(a -> {
                    AntTreeNode dto = new AntTreeNode();
                    dto.setKey(a.getId());
                    dto.setParentKey(a.getParentId());
                    dto.setTitle(a.getName());
                    return dto;
                }).collect(Collectors.toList());
        // 2. 构建树形结构
        Map<String, AntTreeNode> dtoMap = dtoList.stream()
                .collect(Collectors.toMap(AntTreeNode::getKey, dto -> dto));

        List<AntTreeNode> rootList = new ArrayList<>();
        for (AntTreeNode dto : dtoList) {
            if (StringUtils.equals(dto.getParentKey(), "1")) {
                // 如果没有父级，则为根节点
                rootList.add(dto);
            } else {
                // 找到父级节点，将当前节点添加到父级的 children 中
                AntTreeNode parent = dtoMap.get(dto.getParentKey());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(dto);
                }
            }
        }
        return rootList;
    }
}
